﻿$(document).ready(function () {
    formsy.setClickable();

    formsy.setPagination();
});



var formsy = {
    setPagination: function () {
        // get page number from hidden field
        var pageNo = $('#hiddenfieldcurrentpage').val();

        // hide pagination links 
        if (pageNo == 1) {
            $('#linkprev').attr('visible', 'hidden');
        }


        //---
        // do redirect with pageNo as query string
        $('#linknext').click(function () {
            window.location.href = getUrl() + '?page=' + ++pageNo;
        });


        //---
        // do redirect with pageNo as query string
        $('#linkprev').click(function () {
            window.location.href = getUrl() + '?page=' + --pageNo;
        });


        //---
        // strips query string form url
        function getUrl() {
            // get the query string index
            var queryIndex = location.href.indexOf('?page=');

            // return the url without the query string
            return url = location.href.substring(0, queryIndex);
        }
    },


    //---
    // adjust hidden field and display
    adjustPagination: function () {

        // get entrycount
        var entryCount = $('.entrycountvalue');

        // get new count 
        var newEntryCount = $(entryCount).text() - 1;

        // decrement entry count
        $(entryCount).text(newEntryCount);

        // recalculate number of pages
        var pageCount = getPageCount();

        // reset page count display and hidden
        $('.pagecountvalue').text(pageCount);



        // TODO: disable next
        if (getPageCount() == $('#hiddenfieldcurrentpage').val()) {
            // disable "next"
            $('#linknext').html('<span class="faded next">Next</span>');
        }


        //---
        // Returns the number of pages based on entries per page.
        function getPageCount() {
            var entriesPerPage = $('#hiddenfieldentriesperpage').val();

            if ($(entryCount).text() < entriesPerPage) {
                // not enough entries to fill a page
                return 1;
            }

            return Math.round($(entryCount).text() / entriesPerPage);
        }


    },



    setClickable: function () {
        //---
        // click event for editable cell
        $('#FormsyAdmin .cell.editable div.value').click(function () {
            // hide the clicked div
            $(this).toggle();

            // show the editing panel
            $(this).siblings("div.editpanel").toggle();
        });


        //---
        // click event for cancel button
        $(".cancel").click(function () {
            // get .cell text
            var text = $(this).parent().prev("div.value").text()

            // copy text to text area
            $(this).siblings("textarea").val(text);

            // toggle text and edit panel
            $(this).parent().siblings("div.value").toggle();
            $(this).parent().toggle();
        });


        //---
        // click event for accept butotn
        $(".accept").click(function () {
            // get .cell text
            var newText = $(this).siblings("textarea").val();

            // copy textarea text this to .cell
            $(this).parent().prev("div.value").text(newText);

            // toggle .cell and edit panel
            $(this).parent().toggle();
            $(this).parent().prev("div.value").toggle();

            // get data as json
            var data = formsy.getUpdateData(this);

            // do ajax call
            formsy.saveChanges(data);
        });




        //---
        // click event for delete button
        $(".delete").click(function () {
            // relace button with confirmation
            $(this).hide();

            var deleteConfirmation = $(this).siblings(".deleteconfirmation");
            if (deleteConfirmation.length == 0) {
                $(this).parent().append("<div class='deleteconfirmation'><a href='#' class='yes'>Yes</a><span>/</span><a href='#' class='no'>No</a></div>").hide().fadeIn();
            }
            else {
                $(deleteConfirmation).fadeIn();
            }

            // click event for "no"
            $(".deleteconfirmation .no").click(function () {
                $(this).parent().siblings(".delete").show();
                $(this).parent().hide();
            });

            // click event for "yes"
            $(".deleteconfirmation .yes").click(function () {
                // make ajax call to delete
                var data = formsy.getDeleteData(this);

                // do ajax call
                formsy.saveChanges(data);

                // get entry id from this cell
                var id = $(this).parent().siblings("input:hidden").val();

                // select all cells with entryId as hidden field and call fadeOut().remove()
                $(".cell input:hidden").each(function () {
                    if ($(this).val() == id) {
                        // fade out then remove
                        $(this).parent().fadeOut(function () { $(this).remove() });
                    }
                });

                // fade out then remove
                $(this).parent().fadeOut(function () { $(this).remove() });


                // adjust hidden field and display
                formsy.adjustPagination();
            });
        });

    },


    //---
    // ajax call to update/delete database
    saveChanges: function (data) {
        // do post on current page
        $.ajax({
            type: 'POST',
            url: document.location,
            data: data,
            success: function () {
                alert("success");
            },
            dataType: "json"
        });

        // setClickable();
    },


    //---
    // returns json object with data values from page.
    getUpdateData: function (acceptButton) {
        // get entry id
        var id = $(acceptButton).parent().siblings("input:hidden").val();

        // get field name to update (ie. heading == field name)
        var fieldName = $(acceptButton).parent().parent().siblings(".heading").text();

        // get value to save
        var newValue = $(acceptButton).siblings("textarea").val();

        // var formName = $("#hiddenfieldformname").val();

        // create json for data
        var data = {
            "Sender": "Formsy",
            "Action": "Update",
            // "FormName": formName,
            "EntryId": id,
            "FieldName": fieldName,
            "Value": newValue
        }

        return data;
    },



    getDeleteData: function (confirmButton) {
        // get entry id
        var id = $(confirmButton).parent().siblings("input:hidden").val();

        // var formName = $("#hiddenfieldformname").val();

        var data = {
            "Sender": "Formsy",
            "Action": "Delete",
            //"FormName": formName,
            "EntryId": id
        }
        return data;
    }

} // end formsy
